<template>
  <base-table
    :url="url"
    :table-field-list="tableFieldList"
    :submit-form="submitForm"
    :fixed-func-btn="fixedFuncBtn"
    submit-form-title="用户信息"
    @set-form-init-value="setFormInitValue"
    @submit-valid="submitValid"
  >
    <template #submitForm>
      <el-form :model="submitForm" :label-width="100" ref="submitFormRef">
        <el-form-item label="用户名：" prop="username" label-width="100px">
          <el-input v-model="submitForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户类别：" prop="type" label-width="100px">
          <el-select v-model="submitForm.type">
            <template v-for="(item, key) of typeList" :key="key">
              <el-option :value="item.value" :label="item.label"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <template v-if="submitForm.type === '内部员工'">
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="员工工号："
                prop="staffNo"
                label-width="100px"
              >
                <autocomplete-input
                  v-model="submitForm.staffNo"
                  :value-key="selectedPropMap.selectedOriginProp"
                  @get-record="getRecords"
                  @change="
                    setSelectRow(
                      selectedPropMap.setProp,
                      selectedPropMap.setOriginProp,
                      selectedPropMap.selectedProp
                    )
                  "
                  @select="
                    setSelectRow(
                      selectedPropMap.setProp,
                      selectedPropMap.setOriginProp,
                      selectedPropMap.selectedProp
                    )
                  "
                ></autocomplete-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="员工名称："
                prop="staffName"
                label-width="100px"
              >
                <el-input v-model="submitForm.staffName" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </template>
  </base-table>
  <el-dialog
    title="角色分配"
    v-model="setRoleDialogVisible"
    :close-on-click-modal="false"
  >
    <el-tree
      ref="roleTreeRef"
      :data="allRoleList"
      :props="roleTreeProps"
      node-key="id"
      show-checkbox
      highlight-current
      check-strictly
    ></el-tree>
    <template #footer>
      <el-button
        style="float: left"
        type="primary"
        @click="
          submitSetRole();
          changeSetRoleDialogVisible();
        "
        >确认
      </el-button>
      <el-button @click="changeSetRoleDialogVisible()">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Ref, ref } from "vue";

import BaseTable from "@/components/table/basic/BaseTable.vue";
import { User } from "@/models/User";

import api from "@/utils";

import { FixedFuncBtn, TableField, TableUrl } from "@/models/TableSetting.ts";
import { AxiosResponse } from "axios";
import AutocompleteInput from "@/components/input/AutocompleteInput.vue";
import { Role } from "@/models/dataPeople/Role";
import { UserRoleRelation } from "@/models/system/UserRoleRelation";
import { ElMessage } from "element-plus";
import { SelectedPropMap } from "@/components/input/SelectedPropMap";
import { AutocompleteInputEvent } from "@/components/input/AutocompleteInputEvent";

const url = {
  refreshUrl: "/basic-request/User",
  modifyingSingleUrl: "/system/User",
  deleteUrl: "/basic-request/User/batchDelete",
} as TableUrl;

const tableFieldList = [
  {
    filedName: "username",
    label: "用户名",
    minWidth: 200,
  },
  {
    filedName: "type",
    label: "用户类别",
    minWidth: 200,
  },
  {
    filedName: "authorityCode",
    label: "用户授权码",
    minWidth: 200,
  },
  {
    filedName: "queryCode",
    label: "查询授权码",
    minWidth: 200,
  },
  {
    filedName: "staffNo",
    label: "员工工号",
    minWidth: 200,
  },
] as Array<TableField>;

const submitFormRef = ref();
const submitForm = ref({} as User);

const fixedFuncBtn = ref({
  width: 240,
  button: [
    {
      name: "重置密码",
      icon: "Key",
      type: "text",
      method: (row: User) => {
        currentUserId.value = row.id;
        const user = row as User;
        console.log(user.username);
      },
    },
    {
      name: "角色分配",
      icon: "User",
      type: "text",
      method: (row: User) => {
        currentUserId.value = row.id;
        changeSetRoleDialogVisible();
        api.http
          .get("/system/selectRoleIdByUserId/" + row.id)
          .then((res: AxiosResponse) => {
            roleTreeRef.value.setCheckedKeys(res.data);
          });
      },
    },
  ],
} as FixedFuncBtn);

const setFormInitValue = (formType: string, row: User) => {
  if (undefined !== submitFormRef.value) {
    submitFormRef.value.clearValidate();
  }
  switch (formType) {
    case "insert":
      submitForm.value = {
        username: "",
        password: "",
        userNo: "",
        staffNo: "",
        staffName: "",
        createUser: sessionStorage.getItem("token"),
        createGmt: new Date(),
      } as User;
      break;
    case "update":
      submitForm.value = row;
      break;
  }
};

const typeList = [
  {
    label: "内部员工",
    value: "内部员工",
  },
  {
    label: "外部员工",
    value: "外部员工",
  },
  {
    label: "其他用户",
    value: "其他用户",
  },
];

//远程搜索和名称跟随
const selectedPropMap = {
  selectedProp: "staffNo",
  selectedOriginProp: "no",
  setProp: "staffName",
  setOriginProp: "name",
} as SelectedPropMap;

const { getRecords, setSelectRow } = AutocompleteInputEvent(
  "/basic-request/Staff",
  submitForm,
  selectedPropMap
);
/**
 * 提交数据前的校验
 * @param callback 回调函数,将校验结果返还到Table组件中.
 */
const submitValid = (callback: (value: boolean) => void) => {
  submitFormRef.value
    .validate()
    .then(() => {
      callback(true);
    })
    .catch(() => {
      callback(false);
    });
};

const roleTreeRef = ref();

const setRoleDialogVisible = ref(false);
const changeSetRoleDialogVisible = () => {
  setRoleDialogVisible.value = !setRoleDialogVisible.value;
};

const currentUserId = ref();

const submitSetRole = () => {
  const userRoleRelation = [] as UserRoleRelation[];
  roleTreeRef.value.getCheckedKeys().forEach((item: number) => {
    userRoleRelation.push({
      userId: currentUserId.value,
      roleId: item,
      createUser: sessionStorage.getItem("token") as string,
      createGmt: new Date(),
    });
  });
  api.http
    .postJson("/system/setUserRoleRelation", userRoleRelation)
    .then(() => {
      ElMessage.success("设置成功!");
    })
    .catch(() => {
      ElMessage.error("设置失败!");
    });
};

const allRoleList: Ref<Role[]> = ref([]);

const roleTreeProps = {
  children: "children",
  label: "name",
};

const getAllRoleList = () => {
  api.http.get("/basic-request/Role").then((res: AxiosResponse) => {
    allRoleList.value = res.data;
  });
};

getAllRoleList();
</script>
<style scoped></style>
